package com.hhkj.api.wechat.service.biz.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.hhkj.api.wechat.model.req.OpenIdGetReq;
import com.hhkj.api.wechat.model.res.OpenIdGetRes;
import com.hhkj.api.wechat.service.biz.ApiSaleWechatAppBizService;
import com.ruoyi.common.exception.GlobalException;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * ApiWechatAppServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/11/17 20:47
 */
@Service
public class ApiSaleWechatAppBizServiceImpl implements ApiSaleWechatAppBizService {

    // 小程序 appId
    @Value("${wx.appid}")
    private String appid;
    // 小程序 appSecret
    @Value("${wx.secret}")
    private String secret;

    @Override
    public OpenIdGetRes getOpenId(OpenIdGetReq req) {
        //非第三方授权账号获取小程序service
        WxMaService wxMaService = new WxMaServiceImpl();
        WxMaDefaultConfigImpl wxConfig = new WxMaDefaultConfigImpl();
        //小程序 appId
        wxConfig.setAppid(appid);
        //小程序 appSecret
        wxConfig.setSecret(secret);
        wxMaService.setWxMaConfig(wxConfig);
        try {
            WxMaJscode2SessionResult jscode2session = wxMaService.jsCode2SessionInfo(req.getCode());
            return new OpenIdGetRes(jscode2session.getOpenid());
        } catch (WxErrorException e) {
            throw new GlobalException("小程序登录微信失败!");
        }
    }
}
